package AkkaDemos

import akka.actor.{Actor, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

import scala.io.StdIn

object TcpExampleClient {
  def main(args: Array[String]): Unit = {
    //主程序入口
    val (clientHost, clientPort, serverHost, serverPort) = ("127.0.0.1", 7777, "127.0.0.1", 9999)
    val conf = ConfigFactory.parseString(
      s"""|akka.actor.provider="akka.remote.RemoteActorRefProvider"
          |akka.remote.netty.tcp.hostname=$clientHost
          |akka.remote.netty.tcp.port=$clientPort
      """.stripMargin
    )
    val server = ActorSystem("server", conf)
    val customerActor = server.actorOf(Props(new CustomerActor(serverHost, serverPort)), "CustomerActor")
    customerActor ! "start"
    //客户端可以发送消息给服务器
    while (true) {
      println("请输入问题")
      val mes = StdIn.readLine()
      println("您输入的问题:" + mes)
      customerActor ! clientMessage(mes)
    }
  }

  class CustomerActor(serverHost: String, serverPort: Int) extends Actor {
    //定义一个客户端的actorRef
    var serverActorRef: ActorSelection = _

    override def preStart(): Unit = {
      println("preStart 执行")
      serverActorRef = context.actorSelection(s"akka.tcp://server@${serverHost}:${serverPort}/user/ycs")
      println("serverActorRef= " + serverActorRef)
    }

    override def receive: Receive = {
      case "start" => println("start,客户端运行,可以质询问题")
      case serverMessage(mes) => println(s"收到服务器消息: ${mes}")
      case cm: clientMessage => serverActorRef ! cm
    }
  }

}
